#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: robot_admin.py

import sys
import const
import urllib
from pipe_communication import PipeCommunication

message_buffer = ''

def get_input_command():
    """Read input from stdin 

    Each line is a argument
    """
    commands = []
    line = sys.stdin.readline()
    while line:
        commands.append( line.strip() )
        line = sys.stdin.readline()

    command = " ".join( commands )

    return command

def send_command( pipe, command ):
    """Send a command to robot """

    quote_command = urllib.quote( command )
    trail_command = "".join( ( quote_command, "\n" ) )

    encoding = sys.stdin.encoding

    if not encoding: 
        print const.SHELL_UNKNOW_CODING
        encoding = const.SHELL_ENCODING

    decode_command = trail_command.decode( encoding )

    pipe.write( decode_command )

def handler_message( result ):
    """Handle messages

    Handle each line message and detect end flag
    """
    global message_buffer

    message_buffer = "".join( ( message_buffer, result ) )

    message_list = message_buffer.split( '\n' )

    for i, message in enumerate( message_list ):
        if message == const.SHELL_CONTROL_END:
            return False
        elif i == len( message_list ) - 1:
            message_buffer = message
        else:
            print urllib.unquote( message )

    return True

def receive_result( pipe ):
    """Receive result from robot

    Receive results from robot print them into stdout 
    untill receive a END flag
    """
    while True:
        message = pipe.read()

        if not message:
            continue
        
        if not handler_message( message ):
            break;

def main():

    command = ''

    if len( sys.argv ) < 2:
        print """
        Usage: robot_admin.py command 
        """
        sys.exit( 0 )
    elif len( sys.argv ) > 2:
        command = " ".join( sys.argv[1:] )
    else:
        command = " ".join( ( sys.argv[1], get_input_command() ) )

    pipe = PipeCommunication( const.PIPE_OUTPUT, const.PIPE_INPUT )

    send_command( pipe, command )

    receive_result( pipe )
    
    pipe.close()

if __name__ == '__main__':
    main()





# End of robot_admin.py
